package com.ruoyi.common.utils;

import com.ruoyi.common.config.YonBipConfig;
import nccloud.open.api.auto.token.cur.utils.APICurUtils;
import nccloud.open.api.auto.token.itf.IAPIUtils;


public class YonbipTokenUtil
{
    private IAPIUtils util;
    private String token;
    private long tokenExpiryTime;
    private static final long TOKEN_EXPIRY_BUFFER = 5 * 60 * 1000; // 5分钟缓冲时间

    /**
     * 构造函数 - 使用基本参数初始化
     */
    public  YonbipTokenUtil(String ip, String port, String busiCenter, String appId,
                     String appSecret, String publicKey, String nccUser, String password) {
        this.util = new APICurUtils();
        this.util.init(ip, port, busiCenter, appId, appSecret, publicKey, nccUser, password);
    }

    /**
     * 构造函数 - 使用完整参数初始化
     */
    public  YonbipTokenUtil(String ip, String port, String busiCenter, String appId,
                     String appSecret, String publicKey, String nccUser, String password,
                     String tenantId, String secretLevel, String grantType) {
        this.util = new APICurUtils();
        this.util.init(ip, port, busiCenter, appId, appSecret, publicKey, nccUser, password,
                tenantId, secretLevel, grantType);
    }
    public  YonbipTokenUtil(){
        this.util = new APICurUtils();
        this.util.init(
                YonBipConfig.getIp(),
                YonBipConfig.getPort1(),
                YonBipConfig.getBusi_center(),
                YonBipConfig.getApp_id(),
                YonBipConfig.getApp_secret(),
                YonBipConfig.getPublic_key(),
                YonBipConfig.getNcc_user(),
                YonBipConfig.getPassword(),
                YonBipConfig.getTenant_id(),
                YonBipConfig.getSecret_level(),
                YonBipConfig.getGrant_type());
    }

    /**
     * 获取Token（带缓存机制）
     */
    public synchronized String getToken() throws Exception {
        // 如果token为空或已过期，重新获取
        if (token == null || System.currentTimeMillis() > tokenExpiryTime) {
            token = util.getToken();
            // 假设token有效期为1小时，设置过期时间为55分钟后（留出缓冲）
            tokenExpiryTime = System.currentTimeMillis() + (55 * 60 * 1000);
        }
        return token;
    }

    /**
     * 调用API接口
     */
    public String callAPI(String apiUrl, String requestParam) throws Exception {
        util.setApiUrl(apiUrl);
        String currentToken = getToken();
        return util.getAPIRetrun(currentToken, requestParam);
    }

    /**
     * 调用API接口（使用默认参数）
     */
    public String callAPI(String apiUrl, Object requestData) throws Exception {
        String requestParam = requestData instanceof String ?
                (String) requestData :
                "{\"code\":\"" + requestData + "\"}";
        return callAPI(apiUrl, requestParam);
    }

    /**
     * 设置API工具实例（用于测试或自定义实现）
     */
    public void setApiUtils(IAPIUtils util) {
        this.util = util;
    }

    /**
     * 清除缓存的Token
     */
    public void clearToken() {
        this.token = null;
        this.tokenExpiryTime = 0;
    }


   // YonbipTokenUtil yonbipTokenUtil= new YonbipTokenUtil();
   // 获取token

   // // System.out.println(token);
    // 请求的OpenAPI接口地址，注意nccloud前面没有"/"
   // String apiuri = "nccloud/api/uapbd/jdfz/bandoc/byCodeQuery";
   // String requestParam = "{\"code\":\"104397437005\"}";
   // 携带token访问接口，获取结果
   // String result = null;
   //     try
   // {
   //     result = yonbipTokenUtil.callAPI(apiuri, requestParam);
   // } catch (Exception e)
   // {
   //     e.printStackTrace();
   // }
   //     System.out.println(result);
}
